# -*- coding:utf-8

import subprocess
from pyecharts import Page, Grid
from pyecharts import Bar
from pyecharts import Geo, Pie, Map
from flask import Flask, render_template, flash, session, redirect, url_for, request
from flask_sqlalchemy import SQLAlchemy
from flaskext.markdown import Markdown
from flask_wtf import Form
from wtforms import StringField, SubmitField
# from flask_bootstrap import Bootstrap



app = Flask(__name__)

app.config['SECRET_KEY'] = 'asdf#*!`~as?><(%#)(&%$@:'

# sqlalchemy配置
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@localhost/db_mt?charset=utf8mb4'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True


REMOTE_HOST = "static/js"

db = SQLAlchemy(app)
Markdown(app)
# bootstrap = Bootstrap(app)
app.config['BOOTSTRAP_SERVE_LOCAL'] = True

class Deals(db.Model):
    """套餐表"""

    __tablename__ = 'deals'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(50))  # 套餐名称
    price = db.Column(db.Float)   # 价格
    value = db.Column(db.Float)   # 原价
    sales = db.Column(db.Float)   # 销售量
    shopid = db.Column(db.Integer, db.ForeignKey('shop.shopid')) # 外键


    def __repr__(self):
        return "<deals(title='{}', price='{}', value='{}', sales='{}', shopid='{}')>".format(
            self.title, self.price, self.value, self.sales, self.shopid)


class Shop(db.Model):
    """店铺表"""

    __tablename__ = 'shop'  # 表名

    # id = Column(Integer, primary_key=True, autoincrement=True)
    shopid = db.Column(db.Integer, primary_key=True)  # 店铺id
    cateId = db.Column(db.String(10)) # 类别
    title = db.Column(db.String(30))  # 店铺名
    address = db.Column(db.String(1000))    # 店铺地址
    lowestprice = db.Column(db.Float) # 最低消费
    avgprice = db.Column(db.Float)    # 人均消费
    latitude = db.Column(db.String(50))    # 纬度
    longitude = db.Column(db.String(50))   # 经度
    avgscore = db.Column(db.String(20))    # 评分
    comments = db.Column(db.Integer)  # 评论数
    historyCouponCount = db.Column(db.Integer)  # 消费人数
    areaname = db.Column(db.String(20))   # 区域

    def __repr__(self):
        return "<shop(shopid='{}',cateId='{}',title='{}',address='{}',lowestprice='{}',avgprice='{}',latitude='{}'," \
               "longitude='{}',avgscore='{}',comments='{}',historyCouponCount='{}',areaname='{}')>".format(self.shopid,
                self.cateId, self.title, self.address, self.lowestprice, self.avgprice, self.latitude, self.longitude,
                self.avgscore, self.comments, self.historyCouponCount, self.areaname)




def getdata():
    db.create_all()
    num_ms = Shop.query.filter_by(cateId=1).count() # 美食
    num_xy = Shop.query.filter_by(cateId=2).count() # 休闲娱乐
    num_sh = Shop.query.filter_by(cateId=3).count() # 生活服务
    num_lr = Shop.query.filter_by(cateId=22).count()    # 丽人
    num_qz = Shop.query.filter_by(cateId=20007).count() # 亲子
    num_jh = Shop.query.filter_by(cateId=20178).count() # 结婚
    num_yd = Shop.query.filter_by(cateId=20252).count() # 运动健身
    num_jz = Shop.query.filter_by(cateId=20179).count()  # 家装
    num_xx = Shop.query.filter_by(cateId=20274).count() # 学习培训
    num_yl = Shop.query.filter_by(cateId=20285).count() # 医疗

    data = [num_ms, num_xy, num_sh, num_lr, num_qz, num_jh, num_yd, num_jz, num_xx, num_yl]
    return data



def bar_chart():
    page = Page()

    data = getdata()
    print(data)

    value = [20, 190, 253, 77, 40]
    attr = ['沙依巴克区', '新市区', '水磨沟区', '米东区', '天山区']
    map = Map("乌鲁木齐消费", width=800, height=600)
    map.add("", attr, value, maptype='乌鲁木齐', is_visualmap=True,
            visual_text_color='#000')

    # value = [20, 190, 253, 77, 65]
    # attr = ['汕头市', '汕尾市', '揭阳市', '阳江市', '肇庆市']
    # map = Map("广东地图示例", width=1200, height=600)
    # map.add("", attr, value, maptype='广东', is_visualmap=True,
    #         visual_text_color='#000')

    page.add(map)

    attr1 = ["美食", "休闲娱乐", "生活服务", "丽人", "亲子", "结婚", "运动健身", "家装", "学习培训", "医疗"]
    v = [data[0], data[1], data[1], data[3], data[4], data[5], data[6], data[7], data[8], data[9]]
    pie = Pie("乌鲁木齐各个行业比重", title_pos='center')
    pie.add("", attr1, v, radius=[40, 75], label_text_color=None,
            is_label_show=True, legend_orient='vertical',
            legend_pos='left')

    page.add(pie)

    attr2 = ["美食", "休闲娱乐", "生活服务", "丽人", "亲子", "结婚", "运动健身", "家装", "学习培训", "医疗"]
    v1 = [data[0], data[1], data[1], data[3], data[4], data[5], data[6], data[7], data[8], data[9]]
    bar = Bar("乌鲁木齐各个行业比重", height=720)
    bar.add('', attr2, v1)

    page.add(bar)
    return page



@app.route("/pc")
def spider():

    _bar = bar_chart()
    return render_template('pyecharts.html',
                            myechart=_bar.render_embed(),
                            host=REMOTE_HOST,
                            script_list=_bar.get_js_dependencies())


@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        names = request.get_data()
        name = str(names, encoding="utf-8").replace('=','')
        flash("{}爬虫已运行".format(name))
        if name == 'meituan':
            subprocess.Popen("cd /home/leon/bysj;touch meituan.txt", stdout=subprocess.PIPE, shell=True)
        elif name == 'meituan2':
            subprocess.Popen("ping qq.com", stdout=subprocess.PIPE, shell=True)
        elif name == 'news':
            subprocess.Popen("ping qq.com", stdout=subprocess.PIPE, shell=True)
        elif name == 'movie':
            subprocess.Popen("ping qq.com", stdout=subprocess.PIPE, shell=True)

    return render_template('index.html')

@app.route('/spider')
def spider_text():
    return render_template('spider.html')
@app.route('/user')
def user():

    with open('static/spider.md', encoding='utf-8') as mkds:
        mkd = mkds.read()
    return render_template('user.html', mkd=mkd)



@app.errorhandler(404)
def page_not_found(e):
    return render_template("404.html")

@app.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html')



if __name__ == '__main__':
    app.debug = False
    app.run(host='0.0.0.0', port=80)
